<?php
/**
 * User: @yiwan
 * Date: 2019-09-10
 */

namespace Biz\service\esSearch;

use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Search\OrderRefundSearch;
use Biz\tools\FormatDate;
use Doraemon\amqp\Queue;
use Doraemon\tools\Log;

class OrderRefund
{
    // 来源
    const SOURCE_APP = 'app';

    // 场景
    const SCENES_SHOP_ADMIN_ORDER_REFUND = 'shop_admin_order_refund'; // 商城管理后台订单退款列表
    const SCENES_SELLER_ORDER_REFUND = 'seller_order_refund'; // 商家管理后台订单退款列表

    const SCENES_SHOP_ADMIN_ORDER_RIGHT = 'shop_admin_order_right';// 商城管理后台订单维权列表
    const SCENES_SELLER_ORDER_RIGHT = 'seller_order_right'; // 商家管理后台订单维权列表


    /**
     *  搜索方法修改
     * @param array $where
     * @param null $scenes
     * @param int $sortType
     * @param int $page
     * @param int $pageSize
     * @param array $field
     * @return array|mixed
     */
    public static function getList(array $where = [], $scenes = null, $sortType = 1, $page = 1, $pageSize = 20, $field = ['id'])
    {
        $result = ['total' => 0, 'is_over' => 1, 'rows' => []];

        if (is_null($scenes)) {
            return $result;
        } else {
            $where['scenes'] = $scenes;
        }

        if (!isset($where['ORDER'])) {
            $where['ORDER'] = self::sortTypeMapping($sortType);
        }

        $params['query'] = json_encode($where, JSON_UNESCAPED_UNICODE);

        if (is_array($field)) {
            $params['fl'] = implode(",", $field);
        } else {
            $params['fl'] = $field;
        }

        $params['page'] = $page;
        $params['page_size'] = $pageSize;
        $result = OrderRefundSearch::getList($params);
        //var_dump($result);die;
        if (isset($result['data'])) {
            $result = $result['data'];
            $list['total'] = $result['hits']['total'];
            $list['rows'] = $result['hits']['total'] ? self::formatOrderList($result['hits']['hits'], $field) : [];
            $list['is_over'] = count($result['hits']['hits']) >= $pageSize ? 0 : 1;
            if (isset($result['aggregations'])) {
                $list['aggregations'] = $result['aggregations'];
            }
            return $list;
        } else {
            return ['total' => 0, 'is_over' => 1, 'rows' => []];
        }
    }

    private static function sortTypeMapping($sortType)
    {
        $sortMapping = [
            1 => ['addtime' => 'DESC'],
            2 => ['addtime' => 'ASC'],
        ];

        return $sortMapping[$sortType];
    }

    /**
     *  上层代码控制要同步的数据
     * @param $orderRefundInfo
     * @return array|bool
     */
    public static function saveByOrderRefund($orderRefundInfo)
    {
        if (!$orderRefundInfo['id']) {
            return false;
        }

        $result = OrderRefundSearch::save($orderRefundInfo);

        return $result;
    }

    /**
     * 监听binlog同步数据
     * @param $list
     */
    public static function syncSave($list)
    {
        switch ($list['table']) {
            case 'order_refund' :
                $info = self::formatOrderRefundInfo($list['data']);
                self::saveInfo($list, $info);
                break;
            case 'order' :
                $infos = self::formatOrderInfos($list['data']);
                foreach ($infos as $info) {
                    self::saveInfo($list, $info);
                }
                break;
        }
    }

    private static function saveInfo($list, $info)
    {
        $result = OrderRefundSearch::save($info);

        Log::debug('order-debug', $result);

        if ($result['code'] != 1) {
            Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => $list['table'] . '表 同步数据失败 ' . $result,
                'addtime' => date("Y-m-d H:i:s")
            ], Queue::QUEUE_BIZ);
        }
    }

    private static function formatOrderRefundInfo($data)
    {
        $info = [
            'id' => $data['id'],
            'type_refund' => $data['type_refund'],
            'status' => $data['status'],
            'reason' => $data['reason'],
            'refund_order_no' => $data['refund_order_no'],
            'order_no' => $data['order_no'],
            'uid' => $data['uid'],
            'shop_id' => $data['shop_id'],
            'express_no' => $data['express_no'],
            'addtime' => $data['addtime'] == '0000-00-00 00:00:00' ? '0000-01-01 00:00:00' : FormatDate::formatDate($data['addtime']),
            'confirm_time' => $data['confirm_time'] == '0000-00-00 00:00:00' ? '0000-01-01 00:00:00' : FormatDate::formatDate($data['confirm_time']),
            'rights_status' => $data['rights_status'],
            'launch_rights_time' => $data['launch_rights_time'] == '0000-00-00 00:00:00' ? '0000-01-01 00:00:00' : FormatDate::formatDate($data['launch_rights_time']),
            'rights_into_timeout_time' => $data['rights_into_timeout_time'] == '0000-00-00 00:00:00' ? '0000-01-01 00:00:00' : FormatDate::formatDate($data['rights_into_timeout_time']),
            'rights_into_time' => $data['rights_into_time'] == '0000-00-00 00:00:00' ? '0000-01-01 00:00:00' : FormatDate::formatDate($data['rights_into_time']),
        ];
        return $info;
    }

    private static function formatOrderInfos($data)
    {
        $infos = [];
        $info['status'] = $data['status'];
        $orderRefundIds = self::getOrderRefundIdByOrderNo($data['order_no']);
        foreach ($orderRefundIds as $id) {
            $infos[] = ['id' => $id, 'order_info' => $info];
        }
        return $infos;
    }

    private static function getOrderRefundIdByOrderNo($orderNo)
    {
        return mOrderRefund::select('id', ['order_no' => $orderNo]);
    }

    private static function formatOrderList($orderList, $field)
    {
        $list = [];
        foreach ($orderList as $value) {
            if (!is_array($field)) {
                $list[] = $value['_source'][$field];
            } else if (count($field) == 1) {
                $list[] = $value['_source'][current($field)];
            } else {
                $list[] = $value['_source'];
            }
        }

        return $list;
    }
}